/**
 * WebSocket服务 - 管理实时通知连接
 */
class WebSocketService {
  constructor() {
    this.ws = null
    this.url = 'ws://localhost:9090/ws/notifications'
    this.reconnectInterval = 5000 // 5秒重连间隔
    this.maxReconnectAttempts = 5 // 减少最大重连次数
    this.reconnectAttempts = 0
    this.isConnecting = false
    this.messageHandlers = new Map()
    this.connectionState = 'disconnected' // disconnected, connecting, connected, error
    this.heartbeatInterval = null // 心跳定时器
    this.heartbeatTimeout = 30000 // 30秒心跳间隔
    this.lastHeartbeat = null // 最后心跳时间
    this.isManualDisconnect = false // 是否主动断开
    
    // 绑定方法
    this.connect = this.connect.bind(this)
    this.disconnect = this.disconnect.bind(this)
    this.send = this.send.bind(this)
    this.onMessage = this.onMessage.bind(this)
    this.onOpen = this.onOpen.bind(this)
    this.onClose = this.onClose.bind(this)
    this.onError = this.onError.bind(this)
  }

  /**
   * 连接WebSocket
   */
  connect() {
    if (this.isConnecting || this.connectionState === 'connected') {
      console.log('🔌 WebSocket已连接或正在连接中')
      return
    }

    this.isConnecting = true
    this.connectionState = 'connecting'
    
    console.log('🔌 正在连接WebSocket:', this.url)
    
    try {
      this.ws = new WebSocket(this.url)
      
      this.ws.onopen = this.onOpen
      this.ws.onmessage = this.onMessage
      this.ws.onclose = this.onClose
      this.ws.onerror = this.onError
      
    } catch (error) {
      console.error('❌ WebSocket连接失败:', error)
      this.connectionState = 'error'
      this.isConnecting = false
      this.scheduleReconnect()
    }
  }

  /**
   * 连接成功回调
   */
  onOpen(event) {
    console.log('✅ WebSocket连接成功')
    this.connectionState = 'connected'
    this.isConnecting = false
    this.reconnectAttempts = 0
    this.isManualDisconnect = false
    
    // 发送认证信息
    this.sendAuth()
    
    // 启动心跳
    this.startHeartbeat()
    
    // 触发连接成功事件
    this.triggerEvent('connected', event)
  }

  /**
   * 接收消息回调
   */
  onMessage(event) {
    try {
      const data = JSON.parse(event.data)
      console.log('📨 收到WebSocket消息:', data)
      
      // 处理不同类型的消息
      this.handleMessage(data)
      
      // 触发消息事件
      this.triggerEvent('message', data)
      
    } catch (error) {
      console.error('❌ 解析WebSocket消息失败:', error)
    }
  }

  /**
   * 连接关闭回调
   */
  onClose(event) {
    console.log('🔌 WebSocket连接关闭:', event.code, event.reason)
    this.connectionState = 'disconnected'
    this.isConnecting = false
    
    // 停止心跳
    this.stopHeartbeat()
    
    // 触发断开连接事件
    this.triggerEvent('disconnected', event)
    
    // 如果不是主动断开且未达到最大重连次数，尝试重连
    if (!this.isManualDisconnect && event.code !== 1000 && this.reconnectAttempts < this.maxReconnectAttempts) {
      // 根据关闭代码决定重连策略
      if (event.code === 1011) {
        // 服务器内部错误，延迟重连
        console.log('⚠️ 服务器内部错误，延迟重连')
        setTimeout(() => this.scheduleReconnect(), 10000) // 10秒后重连
      } else {
        this.scheduleReconnect()
      }
    } else if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('❌ 达到最大重连次数，停止重连')
    }
  }

  /**
   * 连接错误回调
   */
  onError(error) {
    console.error('❌ WebSocket连接错误:', error)
    this.connectionState = 'error'
    this.isConnecting = false
    
    // 触发错误事件
    this.triggerEvent('error', error)
    
    // 尝试重连
    this.scheduleReconnect()
  }

  /**
   * 发送认证信息
   */
  sendAuth() {
    const token = localStorage.getItem('token')
    if (token) {
      const authMessage = {
        type: 'auth',
        token: token,
        timestamp: Date.now()
      }
      
      console.log('🔐 发送认证信息')
      const success = this.send(authMessage)
      
      if (!success) {
        console.warn('⚠️ 发送认证信息失败')
      }
    } else {
      console.warn('⚠️ 未找到认证token')
    }
  }

  /**
   * 发送消息
   */
  send(data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      try {
        const message = JSON.stringify(data)
        this.ws.send(message)
        console.log('📤 发送WebSocket消息:', data)
        return true
      } catch (error) {
        console.error('❌ 发送WebSocket消息失败:', error)
        return false
      }
    } else {
      console.warn('⚠️ WebSocket未连接，无法发送消息')
      return false
    }
  }

  /**
   * 处理不同类型的消息
   */
  handleMessage(data) {
    const { type, payload } = data
    
    switch (type) {
      case 'notification':
        this.handleNotification(payload)
        break
      case 'ticket_update':
        this.handleTicketUpdate(payload)
        break
      case 'user_online':
        this.handleUserOnline(payload)
        break
      case 'system_message':
        this.handleSystemMessage(payload)
        break
      case 'auth_success':
        console.log('✅ WebSocket认证成功')
        break
      case 'auth_failed':
        console.error('❌ WebSocket认证失败')
        break
      case 'pong':
        console.log('💓 收到心跳响应')
        this.lastHeartbeat = Date.now()
        break
      default:
        console.log('📨 未知消息类型:', type)
    }
  }

  /**
   * 处理通知消息
   */
  handleNotification(payload) {
    console.log('🔔 处理通知消息:', payload)
    
    // 触发通知事件
    this.triggerEvent('notification', payload)
    
    // 显示桌面通知
    this.showDesktopNotification(payload)
  }

  /**
   * 处理工单更新消息
   */
  handleTicketUpdate(payload) {
    console.log('🎫 处理工单更新:', payload)
    
    // 触发工单更新事件
    this.triggerEvent('ticket_update', payload)
  }

  /**
   * 处理用户上线消息
   */
  handleUserOnline(payload) {
    console.log('👤 用户上线:', payload)
    
    // 触发用户上线事件
    this.triggerEvent('user_online', payload)
  }

  /**
   * 处理系统消息
   */
  handleSystemMessage(payload) {
    console.log('⚙️ 系统消息:', payload)
    
    // 触发系统消息事件
    this.triggerEvent('system_message', payload)
  }

  /**
   * 显示桌面通知
   */
  showDesktopNotification(payload) {
    if (!('Notification' in window)) {
      console.warn('⚠️ 浏览器不支持桌面通知')
      return
    }

    if (Notification.permission === 'granted') {
      const notification = new Notification(payload.title || '新通知', {
        body: payload.content || payload.message,
        icon: payload.icon || '/favicon.ico',
        tag: payload.id || 'notification',
        data: payload
      })

      notification.onclick = () => {
        window.focus()
        notification.close()
        
        // 触发通知点击事件
        this.triggerEvent('notification_click', payload)
      }
    } else if (Notification.permission !== 'denied') {
      Notification.requestPermission().then(permission => {
        if (permission === 'granted') {
          this.showDesktopNotification(payload)
        }
      })
    }
  }

  /**
   * 安排重连
   */
  scheduleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('❌ 达到最大重连次数，停止重连')
      return
    }

    this.reconnectAttempts++
    // 使用指数退避算法，但限制最大延迟
    const delay = Math.min(this.reconnectInterval * Math.pow(2, this.reconnectAttempts - 1), 30000)
    
    console.log(`🔄 ${delay/1000}秒后尝试第${this.reconnectAttempts}次重连`)
    
    setTimeout(() => {
      if (!this.isManualDisconnect) {
        this.connect()
      }
    }, delay)
  }

  /**
   * 断开连接
   */
  disconnect() {
    console.log('🔌 主动断开WebSocket连接')
    this.isManualDisconnect = true
    
    // 停止心跳
    this.stopHeartbeat()
    
    if (this.ws) {
      this.ws.close(1000, '主动断开连接')
      this.ws = null
    }
    this.connectionState = 'disconnected'
    this.isConnecting = false
    this.reconnectAttempts = 0
  }

  /**
   * 注册消息处理器
   */
  on(eventType, handler) {
    if (!this.messageHandlers.has(eventType)) {
      this.messageHandlers.set(eventType, [])
    }
    this.messageHandlers.get(eventType).push(handler)
  }

  /**
   * 移除消息处理器
   */
  off(eventType, handler) {
    if (this.messageHandlers.has(eventType)) {
      const handlers = this.messageHandlers.get(eventType)
      const index = handlers.indexOf(handler)
      if (index > -1) {
        handlers.splice(index, 1)
      }
    }
  }

  /**
   * 触发事件
   */
  triggerEvent(eventType, data) {
    if (this.messageHandlers.has(eventType)) {
      const handlers = this.messageHandlers.get(eventType)
      handlers.forEach(handler => {
        try {
          handler(data)
        } catch (error) {
          console.error(`❌ 事件处理器执行失败 (${eventType}):`, error)
        }
      })
    }
  }

  /**
   * 获取连接状态
   */
  getConnectionState() {
    return this.connectionState
  }

  /**
   * 检查是否已连接
   */
  isConnected() {
    return this.connectionState === 'connected' && this.ws && this.ws.readyState === WebSocket.OPEN
  }

  /**
   * 启动心跳
   */
  startHeartbeat() {
    this.stopHeartbeat() // 先停止之前的心跳
    
    this.heartbeatInterval = setInterval(() => {
      if (this.isConnected()) {
        this.sendPing()
      } else {
        this.stopHeartbeat()
      }
    }, this.heartbeatTimeout)
    
    console.log('💓 心跳机制已启动')
  }

  /**
   * 停止心跳
   */
  stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
      this.heartbeatInterval = null
      console.log('💓 心跳机制已停止')
    }
  }

  /**
   * 发送心跳
   */
  sendPing() {
    if (this.isConnected()) {
      this.send({
        type: 'ping',
        timestamp: Date.now()
      })
      this.lastHeartbeat = Date.now()
    }
  }

  /**
   * 重置重连计数器
   */
  resetReconnectAttempts() {
    this.reconnectAttempts = 0
  }
}

// 创建全局WebSocket服务实例
const wsService = new WebSocketService()

export default wsService
